package com.example.myapplication;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;

import android.os.Environment;
import android.provider.MediaStore;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

import androidx.annotation.Nullable;
import androidx.core.content.FileProvider;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class MainActivity extends Activity {
    private ImageView imageView = null;
    private Button btnTakePicture = null;
    File showPIC;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        imageView = (ImageView) findViewById(R.id.imageView);
        btnTakePicture = (Button) findViewById(R.id.btnTakePicture);

        if (Build.VERSION.SDK_INT>=23){
            requestPermissions(new String[]{Manifest.permission.CAMERA,Manifest.permission.WRITE_EXTERNAL_STORAGE},2);
        }//请求权限
        btnTakePicture.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                dispafuckpic();

            }
        });

    }

    private void dispafuckpic() {
        Intent takepic=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (takepic.resolveActivity(getPackageManager())!=null){
            //这代表你的app可以允许相机
            File photofile=null;
            try{
                photofile=cratephotofile();//去创建文件方法,获得图片路径创建的
                showPIC=photofile;
                if (photofile!=null) {
                    String pathtofile = photofile.getAbsolutePath();
                    Uri photouri= FileProvider.getUriForFile(MainActivity.this,"com.example.myapplication.MainActivity",photofile);
                    //把这个图片和其他app分享，AUTHORITY是自己定义的,第三个必须是完整的图片路径
                    takepic.putExtra(MediaStore.EXTRA_OUTPUT,photouri);
//把share的Uri放进选好的路径
                    startActivityForResult(takepic,1);
                }
            }
            catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {

        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode==RESULT_OK){
            if (requestCode==1){
                int degree = ImageDispose.readPictureDegree(showPIC.getAbsolutePath());

                System.out.println(degree+"========");

                // 设置参数
                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inJustDecodeBounds = true; // 只获取图片的大小信息，而不是将整张图片载入在内存中，避免内存溢出
                BitmapFactory.decodeFile(showPIC.getPath(), options);
                int height = options.outHeight;
                int width= options.outWidth;
                int inSampleSize =1; // 默认像素压缩比例，压缩为原图的1/2
                int minLen = Math.min(height, width); // 原图的最小边长
                System.out.println(minLen+"=====milLen=======");
                if(minLen > 2000) { // 如果原始图像的最小边长大于2000dp（此处单位我认为是dp，而非px）
                    inSampleSize =2;
                }
                options.inJustDecodeBounds = false; // 计算好压缩比例后，这次可以去加载原图了
                options.inSampleSize = inSampleSize; // 设置为刚才计算的压缩比例
                Bitmap bm = BitmapFactory.decodeFile(showPIC.getPath(), options); // 解码文件
                bm = ImageDispose.rotaingImageView(degree, bm);

                ByteArrayOutputStream bos = new ByteArrayOutputStream();

                bm.compress(Bitmap.CompressFormat.JPEG,80,bos);
                try {
                    bos.flush();
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                byte[] bb = bos.toByteArray();
                String image = Base64.encodeToString(bb, Base64.NO_WRAP);

            }
        }
    }

    public File  cratephotofile() throws IOException {//返回一个File类的文件
        String name=new SimpleDateFormat("YYYYMMdd_HHmmss").format(new Date());
//年月日小时分秒
        File stordir= Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
        //获得公共目录下的图片文件路径
        File image=File.createTempFile(name,".jpg",stordir);

        /**
         * 获取图片的旋转角度，有些系统把拍照的图片旋转了，有的没有旋转
         */
        return image;
    }

}
